package jwdt.xadmin.bbs.service.impl;

import java.util.ArrayList;
import java.util.List;

import jwdt.common.bean.Tree;
import jwdt.common.dao.BaseDao;
import jwdt.xadmin.bbs.bean.TBclass;
import jwdt.xadmin.bbs.service.ClassManageService;

import com.ezerg.db.Jdb;
import com.ezerg.db.ext.PageUtil;
import com.ezerg.fastjson.JSON;

public class ClassManageServiceImpl implements ClassManageService {

	private BaseDao<TBclass> baseDao;
	
	public void setBaseDao(BaseDao<TBclass> baseDao) {
		this.baseDao = baseDao;
	}
	
	@Override
	public PageUtil doList(PageUtil pu, TBclass tc) throws Exception{
		String where = "";
		String sql = " order by id desc";
		pu.doList(TBclass.class,where+sql);
		//创造json数据对象
		return pu;
	}
	

	@Override
	public TBclass doLoad(int id) throws Exception {
		return baseDao.doLoadObj(TBclass.class, id);
	}
	
	@Override
	public String doSave(TBclass obj,int id) throws Exception {
			if(id==0){
				return baseDao.doAddObj(obj);
			}
			return baseDao.doUpdateObj(TBclass.class, id, obj);
		}
	
	@Override
	public String doDel(int id) throws Exception{
		return baseDao.doDelObj(TBclass.class,id);
	}

	@Override
	@SuppressWarnings("unchecked")
	public String doListForTree() throws Exception {
		List<Tree> treeList = new ArrayList<Tree>();
		List<TBclass> list = Jdb.get().query(TBclass.class,"fid=0 and zt=1 order by id");
		Tree tree = new Tree();
		tree.setId("0");
		tree.setText("全部分类");
		tree.setIconCls("icon-sum");
		tree.setChildren(treeList(list));
		treeList.add(tree);
		return JSON.toJSONString(treeList);
	}
	
	@SuppressWarnings("unchecked")
	public List<Tree> treeList(List<TBclass> list){
		List<Tree> treeList = new ArrayList<Tree>();
		for (TBclass dc : list) {
			Tree tree = new Tree();
			tree.setId(dc.getId()+"");
			tree.setText(dc.getName());
			if(!dc.getChildren().isEmpty()){
				tree.setChildren(treeList(dc.getChildren()));
			}
			treeList.add(tree);
		}
		return treeList;
	}

	@Override
	public String doUpdateState(int id, String result) throws Exception {
		return baseDao.doIntUpdateState(TBclass.class, "id="+id, result);
	}
	
}
